{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Crew + Klavis AI Integration\n",
    "\n",
    "This tutorial demonstrates how to build AI agents using CrewAI with Klavis Strata MCP servers for enhanced functionality."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "Before we begin, you'll need:\n",
    "\n",
    "- **OpenAI API key** - Get at [openai.com](https://openai.com/)\n",
    "- **Klavis API key** - Get at [klavis.ai](https://klavis.ai/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install the required packages\n",
    "%pip install -q klavis python-dotenv crewai crewai-tools[mcp] openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import webbrowser\n",
    "from crewai import Agent, Task, Crew, Process\n",
    "from crewai_tools import MCPServerAdapter\n",
    "from klavis import Klavis\n",
    "from klavis.types import McpServerName\n",
    "\n",
    "# Set environment variables\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"YOUR_OPENAI_API_KEY\"  # Replace with your actual OpenAI API key\n",
    "os.environ[\"KLAVIS_API_KEY\"] = \"YOUR_KLAVIS_API_KEY\"  # Replace with your actual Klavis API key"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Create Strata MCP Server\n",
    "\n",
    "Create Strata MCP server that combines multiple services (Gmail and Slack) for enhanced agent capabilities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "klavis_client = Klavis(api_key=os.getenv(\"KLAVIS_API_KEY\"))\n",
    "\n",
    "# Create a Strata MCP server with Gmail and Slack integrations\n",
    "response = klavis_client.mcp_server.create_strata_server(\n",
    "    servers=[McpServerName.GMAIL, McpServerName.SLACK], \n",
    "    user_id=\"1234\"\n",
    ")\n",
    "\n",
    "print(f\"🔗 Strata MCP server created at: {response.strata_server_url}\")\n",
    "\n",
    "# Handle OAuth authorization if needed\n",
    "if response.oauth_urls:\n",
    "    for server_name, oauth_url in response.oauth_urls.items():\n",
    "        webbrowser.open(oauth_url)\n",
    "        print(f\"🔐 Opening OAuth authorization for {server_name}: {oauth_url}\")\n",
    "        input(f\"Press Enter after completing {server_name} OAuth authorization...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Create and Run CrewAI Agent with MCP Tools\n",
    "\n",
    "Set up the CrewAI agent with tools from the Strata MCP server, create a task, and execute it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure MCP server parameters\n",
    "klavis_server_params = [\n",
    "    {\n",
    "        \"url\": response.strata_server_url,\n",
    "        \"transport\": \"streamable-http\"\n",
    "    }\n",
    "]\n",
    "\n",
    "# Configure your query\n",
    "user_query = \"Check my latest 5 emails and summarize them in a Slack message to #general\"  # Change this query as needed\n",
    "\n",
    "# Create and run the crew with MCP tools\n",
    "with MCPServerAdapter(klavis_server_params) as all_mcp_tools:\n",
    "    print(f\"✅ Available tools: {[tool.name for tool in all_mcp_tools]}\")\n",
    "\n",
    "    # Create CrewAI agent with MCP tools\n",
    "    klavis_agent = Agent(\n",
    "        role=\"Klavis Query Assistant\",\n",
    "        goal=\"Assist the user with their query using available tools\",\n",
    "        backstory=\"Expert at assisting users with their queries using available tools\",\n",
    "        tools=all_mcp_tools,\n",
    "        verbose=False,\n",
    "        llm=\"gpt-4o\"  # Using OpenAI GPT-4o model\n",
    "    )\n",
    "\n",
    "    # Create a task for the agent\n",
    "    klavis_task = Task(\n",
    "        description=f\"Answer the user's query: {user_query}\",\n",
    "        expected_output=\"Provide a detailed response to the user's query\",\n",
    "        agent=klavis_agent\n",
    "    )\n",
    "\n",
    "    # Create a crew with the agent and task\n",
    "    crew = Crew(\n",
    "        agents=[klavis_agent],\n",
    "        tasks=[klavis_task],\n",
    "        process=Process.sequential,\n",
    "        verbose=True\n",
    "    )\n",
    "\n",
    "    print(\"🚀 Executing crew...\")\n",
    "    \n",
    "    # Execute the crew\n",
    "    result = crew.kickoff()\n",
    "    \n",
    "    # Print the final AI response\n",
    "    print(\"\\n✅ Result:\")\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "🎉 Congratulations! You've successfully created a CrewAI agent that can:\n",
    "\n",
    "1. **Read emails** using the Gmail MCP server\n",
    "2. **Send Slack messages** using the Slack MCP server\n",
    "3. **Coordinate multiple services** through Klavis Strata MCP integration\n",
    "\n",
    "This demonstrates the power of combining CrewAI's agent framework with Strata MCP server for building sophisticated AI workflows that can interact with multiple external services seamlessly."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
